# -*- coding: utf-8 -*-
"""
@Time ： 2022/8/2 21:17
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：图文验证码
@installer：pip install requests
"""
from hashlib import md5
import requests


class Verify:
    def __init__(self, username, password, soft_id):
        """
        :param username: 用户名
        :param password: 密码
        :param soft_id: 软件id
        """
        self.username = username
        # md5加密
        password = password.encode('utf8')
        self.password = md5(password).hexdigest()

        self.soft_id = soft_id
        # 初始化参数
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        # 添加头
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def get_verify(self, im, codetype='1902'):
        """
        im: 图片地址
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        # 打开图片为二进制
        im = open(im, 'rb').read()
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        print(r.json())
        try:
            ver= r.json().get('pic_str')
        except Exception as e:
            print(e.__str__())
            ver = 'None'

        return ver


if __name__ == '__main__':
    # 创建对象
    verify = Verify('wuqingfqng','wuqing&fqng','904357')
    # 调用方法，获取验证码
    ver = verify.get_verify('./bb.png','9004')
    print(ver)
